package eureka.ui.auction;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import eureka.domain.account.WebsiteUser;
import eureka.domain.auction.Auction;
import eureka.domain.auction.AuctionState;
import eureka.exceptions.DatabaseException;
import eureka.service.auction.IAuctionService;
import eureka.service.auction.impl.AuctionService;
import util.web.page.PageBean;

/**
 * Servlet implementation class ShowOngoingAsOwner
 */
@WebServlet("/Auctions/ShowOngoingAsOwner")
public class ShowOngoingAsOwner extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
	private IAuctionService auctionService = new AuctionService();
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ShowOngoingAsOwner() {
        super();
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		HttpSession session = request.getSession();
		
		WebsiteUser user = (WebsiteUser) session.getAttribute("user");
		if (user == null) {
			response.sendError(403);
			return;
		}
		

		String pagesizestr = request.getParameter("pageSize");
		String currentpagestr = request.getParameter("curPage");

		long pagesize = 0;
		long curpage = 0;
		try {
			pagesize = Long.parseLong(pagesizestr);
			if (pagesize <= 0 || pagesize >= 100)
				pagesize = 20;

		} catch (Exception e) {
			pagesize = 20;
		}
		try {
			curpage = Long.parseLong(currentpagestr);
			if (curpage <= 0)
				curpage = 1;
		} catch (Exception e) {
			curpage = 1;
		}
		
		PageBean<Auction> page = new PageBean<Auction>();
		page.setCurrentPage(curpage);
		page.setPageSize(pagesize);
		List<Auction> list = null;
		
		try {
			list = auctionService.getAuctions(0, 0, user.getUID(), AuctionState.Ongoing, 0, page.getRecordStart(), page.getPageSize());
			page.setRecords(list, 
					auctionService.getAuctionsCount(0, 0, user.getUID(), AuctionState.Ongoing, 0));
		} catch (DatabaseException e) {
			response.sendError(500);
			return;
		}
		
		request.setAttribute("page", page);
		request.getRequestDispatcher("listongoingasowner.jsp").forward(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}
